from copy import deepcopy
from typing import Dict, List, Any
import asyncio
import json

from my_utils.api_request import async_query_by_paper_id


# -------------------------------------------- 解析递归大纲的内容，获取全部叶节点，并更新全部叶节点 --------------------------------------------
class OutlineUtils:
    @staticmethod
    def get_all_leaf_nodes(doc: Dict[str, Any]) -> List[Dict[str, Any]]:
        """ 获取所有叶子节点的完整信息 """
        nodes = []

        def traverse(node: Dict[str, Any]) -> None:
            if not node.get('children'):  # 是叶子节点
                # 复制节点的所有信息
                node_info = {
                    'title': node.get('title', ''),
                    'content': node.get('content', ''),
                    'refs': node.get('refs', [])
                }
                nodes.append(node_info)
            else:  # 不是叶子节点，继续遍历
                for child in node['children']:
                    traverse(child)

        # 从第一级节点开始遍历
        for node in doc['children']:
            traverse(node)

        return nodes

    @staticmethod
    def update_leaf_nodes(doc: Dict[str, Any], new_nodes: List[Dict[str, Any]]) -> Dict[str, Any]:
        """ 更新所有叶子节点的完整信息 """
        index = 0

        def traverse(node: Dict[str, Any]) -> None:
            nonlocal index
            if not node.get('children'):  # 是叶子节点
                if index < len(new_nodes):
                    # 更新节点的所有信息
                    node['title'] = new_nodes[index].get('title', node.get('title', ''))
                    node['content'] = new_nodes[index].get('content', node.get('content', ''))
                    node['refs'] = new_nodes[index].get('refs', node.get('refs', []))
                    index += 1
            else:  # 不是叶子节点，继续遍历
                for child in node['children']:
                    traverse(child)

        # 创建文档的深拷贝以避免修改原始文档
        import copy
        doc_copy = copy.deepcopy(doc)

        # 从第一级节点开始遍历
        for node in doc_copy['children']:
            traverse(node)

        return doc_copy

    @staticmethod
    def get_table_of_contents(doc: Dict[str, Any]) -> str:
        """ 获取文档的目录结构 """
        toc = []

        def traverse(node: Dict[str, Any], level: int = 0) -> None:
            # 添加缩进
            indent = "    " * level
            # 添加标题
            toc.append(f"{indent}{node['title']}")

            # 遍历子节点
            if node.get('children'):
                for child in node['children']:
                    traverse(child, level + 1)

        # 添加文档标题
        toc.append(doc['title'])

        # 从第一级节点开始遍历
        for node in doc['children']:
            traverse(node)

        # 拼接所有标题，使用换行符分隔
        return "\n".join(toc)

    @staticmethod
    def fill_parent_contents(doc: Dict[str, Any]) -> Dict[str, Any]:
        """ 自底向上填充父节点的内容 """

        def merge_children_content(node: Dict[str, Any]) -> str:
            """递归合并子节点内容，并在每个内容前添加标题"""
            # 如果是叶子节点，返回标题+内容
            if not node.get('children'):
                content = node.get('content', '').strip()
                if content:
                    return f"{node['title']}\n\n{content}"
                return ''

            # 如果有子节点，先递归处理所有子节点
            children_contents = []
            for child in node['children']:
                child_content = merge_children_content(child)
                if child_content:  # 只添加非空内容
                    children_contents.append(child_content)

            # 合并所有子节点的内容
            merged_content = '\n\n'.join(children_contents)

            # 更新当前节点的content，并加上自己的标题
            node['content'] = f"{node['title']}\n\n{merged_content}"
            return node['content']

        # 创建文档副本
        doc_copy = deepcopy(doc)

        # 处理每个顶级节点
        root_contents = []
        for node in doc_copy['children']:
            content = merge_children_content(node)
            if content:
                root_contents.append(content)

        # 更新文档的主要内容
        doc_copy['content'] = '\n\n'.join(root_contents)

        return doc_copy

